package com.mm.learn.shopping.cart;

import com.mm.learn.constant.AuthConstant;
import com.mm.learn.shopping.cart.vo.Cart;
import com.mm.learn.shopping.cart.vo.CartItem;
import com.mm.learn.shopping.cart.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author wdd
 */
@Controller
public class CartController {


    @Autowired
    CartService cartService;


    @GetMapping("/countItem")
    public String itemCount(Long skuId,Integer num) {
        cartService.changeItemCount(skuId,num);
        return "redirect:/cart.html";
    }

    /**
     * 浏览器有一个 cookie;user-key;标识用户身份，一个月后过期;
     * 如果第一次使用jd的购物车功能，都会给一个临时的用户身份
     * 测览器以后保存，每次访间都会带上这个 cookie;
     * 登录session有
     * 没登录：按照 cokie里面带来user-key来做
     * 第一次：如果没有临时用户，帮忙创建一个临时用户。
     *
     * @return
     */
    @GetMapping("/cart.html")
    public String cartListPage(Model model) {
        Cart cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    /**
     * 登录
     *
     * @param session
     * @return
     */
    @GetMapping("/login/{id}")
    @ResponseBody
    public String login(HttpSession session, @PathVariable Long id) {
        MemberRespVo memberRespVo = new MemberRespVo();
        memberRespVo.setUserId(id);
        session.setAttribute(AuthConstant.LOGIN_USER, memberRespVo);
        return "登录成功";
    }


    /**
     * 添加购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @GetMapping("/addToCart")
    public String addToCart(Long skuId, Integer num, RedirectAttributes mode) {
        CartItem cartItem = cartService.addToCart(skuId, num);
        mode.addAttribute("skuId", skuId);
        return "redirect:/addToCartSuccessPage.html";
    }

    @GetMapping("/addToCartSuccessPage.html")
    public String addToCartSuccessPage(Long skuId, Model model) {
        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("cartItem", cartItem);
        return "success";
    }


}
